package com.longge.websocket.interceptor;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor  {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		 ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
	     String ticket = serverRequest.getServletRequest().getParameter("ticket");
	     String userId = serverRequest.getServletRequest().getParameter("uid");
	     if(StringUtils.isAnyBlank(ticket, userId)) {
	    	 return false;
	     }
		attributes.put("uid", userId);
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
	}

}
